package com.learn.atomic;

import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/21
 */
public class TestAtomicStampReference {
    private static final Logger log = Logger.getLogger(TestAtomicStampReference.class);

    static AtomicStampedReference<String> ref = new AtomicStampedReference<>("A",0);

    public static void main(String[] args) throws InterruptedException {
        log.debug("main start...");
//        获取值A
//        这个共享变量被其它线程修改过？
        String prev = ref.getReference();
//        获取版本号
        int stamp = ref.getStamp();
        log.debug(stamp);
        other();
        TimeUnit.SECONDS.sleep(1);
        log.debug(stamp);
//        尝试改为C
        log.debug("change A->C " + ref.compareAndSet(prev, "C",stamp,stamp+1));
    }

    private static void other() throws InterruptedException {
        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug(stamp);
            log.debug("change A->B " + ref.compareAndSet(ref.getReference(), "B",stamp,stamp+1));
        }, "t1").start();

        Thread.sleep(500);

        new Thread(() -> {
            int stamp = ref.getStamp();
            log.debug(stamp);
            log.debug("change B->A " + ref.compareAndSet(ref.getReference(), "A",stamp,stamp+1));
        }, "t2").start();
    }

}
